import { t } from 'i18next'
import React, { FC, useEffect, useRef, useState } from 'react'
import { Button, Modal, Search, Space } from '@kedacom/react-next'
import {
	IconActionEditBatchPoll,
	IconActionEditBatchPollDisabled,
	IconTips,
	StyledFooter,
	StyledMemberList,
} from './style'
import { DragDropContextProvider, Draggable, Droppable } from '@/plugins/dnd'
import AutoSizer from 'react-virtualized-auto-sizer'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import { useDebounceEffect } from 'ahooks'
import { ListItem } from './listItem'
import shallow from 'zustand/shallow'
import { Mt, MtEntity, revert_mt } from '@/api/manager/mt'
import { Poll } from '../interface'
import PollModal, { PollModalRef } from './PollModal'
import { getItemByMtKey } from '../../main/table/all/utils'
import { useTableAllStore } from '../../main/table/all/store'
import { isMatch } from '@/pages/manager/utils/utils'
import { ListItemGhost } from '@/pages/manager/components'
import { useBatchMemberListStore } from './store'
import { DropData, IMcc } from '@/api/manager/type'
import { dealDrop, listOrderClick } from '@/utils/listSlice'
import { useVmpTypeStore } from '../store.get'
import { MccModel } from '../../main/table/all/translator'

interface RowRendererProps extends ListChildComponentProps {
	data: Mt[]
}
const rowRenderer = React.memo(({ data, index, style }: RowRendererProps) => {
	const rowData = data[index]
	const useStore = useVmpTypeStore((state) => state.getStore())
	const canDrag = useStore((state) => (!state._isStart || state._isEdit) && state.data.mode === 4)
	const actualSearchVal = useBatchMemberListStore((state) => state.actualSearchVal, shallow)
	const dataTransfer = () => {
		return {
			data: { mt: revert_mt(rowData) },
			from: 'BatchMemberList',
		}
	}
	return (
		<Draggable
			canDrag={canDrag && actualSearchVal === ''}
			index={index}
			dataTransfer={dataTransfer}
			ghostRender={<ListItemGhost data={rowData} />}
			style={style}
		>
			<ListItem mcc={rowData} />
		</Draggable>
	)
})
export const BatchMemberList: FC<{ pollData: Poll | null }> = ({ pollData }) => {
	const useStore = useVmpTypeStore((state) => state.getStore())
	const canDrag = useStore((state) => (!state._isStart || state._isEdit) && state.data.mode === 4)
	const selectedMtKeys = useStore((state) => state.memberList.map((x) => x.mt_key), shallow)
	const {
		_pollMembers,
		update,
		poll_select_mt_key,
		_isStart,
		_isEdit,
		batchMembers,
		pollModalIsOpen,
		PollPlanDetail,
	} = useStore(
		(state) => ({
			_pollMembers: state._pollMembers,
			poll_select_mt_key: state.poll_select_mt_key,
			_isStart: state._isStart,
			_isEdit: state._isEdit,
			batchMembers: state.batchMembers,
			pollModalIsOpen: state.pollModalIsOpen,
			PollPlanDetail: state.PollPlanDetail,
			update: state.update,
		}),
		shallow
	)
	const { actualSearchVal, updateBatchMemberListStore, pollMembers, poll_select_mt_key_list } =
		useBatchMemberListStore(
			(state) => ({
				poll_select_mt_key_list: state.poll_select_mt_key_list,
				pollMembers: state.pollMembers,
				actualSearchVal: state.actualSearchVal,
				updateBatchMemberListStore: state.update,
			}),
			shallow
		)
	const tableAll = useTableAllStore((state) => state.tree)
	const [searchVal, setSearchVal] = useState('')
	const [show_pollMembers, setShowPollMembers] = useState<Mt[]>([])
	const setPollMembers = (_d: Mt[]) => {
		updateBatchMemberListStore({ pollMembers: _d })
	}
	// const [pollMembers, setPollMembers] = useState<Mt[]>([])
	const handleSearch = (val: string) => {
		setSearchVal(val)
	}
	useDebounceEffect(
		() => {
			updateBatchMemberListStore({ actualSearchVal: searchVal })
		},
		[searchVal],
		{
			wait: 250,
		}
	)
	const initData = (pollData: Poll | null) => {
		const _tree = getItemByMtKey(tableAll, '0.0.0.0_0')
		if (pollData) {
			const _poll_members = pollData.members.map((item) => {
				const mt_key = item.mtKey
				const sourceItem: MccModel<IMcc> | undefined = _tree?.children.find((x) => {
					return x.mcc.isMt && x.mtKey === mt_key
				})
				if (sourceItem && sourceItem.mcc.isMt) {
					return sourceItem.mcc
				}
				return item
			})
			setPollMembers(_poll_members)
		} else {
			const _poll_members = batchMembers
				.filter((x) => x.isMt)
				.map((item) => {
					const mt_key = item.mtKey
					const sourceItem: MccModel<IMcc> | undefined = _tree?.children.find((x) => {
						return x.mcc.isMt && x.mtKey === mt_key
					})
					if (sourceItem && sourceItem.mcc.isMt) {
						return sourceItem.mcc
					}
					return item
				})
			setPollMembers(_poll_members)
		}
	}
	/**初始化批量轮询列表 */
	useEffect(() => {
		initData(pollData)
	}, [pollData])
	useEffect(() => {
		initData(PollPlanDetail)
	}, [PollPlanDetail])
	/**更新全局 */
	useEffect(() => {
		update({ _pollMembers: pollMembers })
	}, [pollMembers])
	/**展示批量轮询列表依据编辑中和画面合成开启状态 */
	useEffect(() => {
		const batchpoll_pollMembers = pollMembers.filter((v) => isMatch(v, actualSearchVal))
		setShowPollMembers(batchpoll_pollMembers)
	}, [actualSearchVal, pollMembers, _isStart, _isEdit, selectedMtKeys])
	const listRef = useRef<List<Mt[]> | null>(null)
	useEffect(() => {
		if (_isEdit || !_isStart) {
		} else {
			//滚动到指定位置
			if (listRef.current) {
				let index = pollMembers.findIndex((x) => x.mtKey === selectedMtKeys[0])
				if (index !== -1) {
					listRef.current.scrollToItem(index, 'start')
				}
			}
		}
	}, [pollMembers, _isStart, _isEdit, selectedMtKeys])
	/**依据更新列表状态*/
	useEffect(() => {
		if (tableAll) {
			const _tree = getItemByMtKey(tableAll, '0.0.0.0_0')
			const _poll_members = useBatchMemberListStore.getState().pollMembers.map((item) => {
				const mt_key = item.mtKey
				const sourceItem = _tree?.children.find((x) => {
					return x.mcc.isMt && x.mtKey === mt_key
				})
				if (sourceItem && sourceItem.mcc.isMt) {
					return sourceItem.mcc
				}
				return item
			})
			setPollMembers(_poll_members)
		}
	}, [tableAll])
	const handleDrop = (dataTransfer: DropData<MtEntity & { isMt: true }>, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt && dataTransfer.from === 'BatchMemberList') {
			let mt = dataTransfer.data.mt
			if (canDrag && actualSearchVal === '') {
				const result = dealDrop(show_pollMembers, {
					mts: [new Mt(mt)],
					dropIndex: index,
					isOther: false,
				})
				setPollMembers(result)
			}
		}
	}
	const pollModalRef = useRef<PollModalRef>(null)
	const okFn = () => {
		let data = pollModalRef.current?.getValue()
		if (data) {
			setPollMembers(data)
			update({ pollModalIsOpen: false })
			pollModalRef.current?.reset()
		}
	}
	const [modalList, setModalList] = useState<Mt[]>([])
	const openModal = () => {
		if (canDrag) {
			setModalList(() => [...pollMembers])
			update({ pollModalIsOpen: true })
		}
	}
	const handleOrder = (order: 'up' | 'top' | 'bottom' | 'down') => {
		const __pollMembers = _pollMembers
		const result = __pollMembers.map((mt) => {
			return {
				mcc: mt,
				status: { checked: poll_select_mt_key_list.includes(mt.mtKey) },
			}
		})
		let mts = listOrderClick(result, order).map((item) => {
			return item.mcc
		})
		setPollMembers([...mts])
		update({ _pollMembers: [...mts] })
	}
	return (
		<StyledMemberList className="member-list-wrap">
			<div className="top-size">
				<span className="list-header-title">{t('轮询方列表', { context: 'SC1' })}</span>
				<span className="list-select">{t('已选')}</span>
				<span className="list-select-num">{show_pollMembers.length}</span>
				<span onClick={openModal}>
					{!canDrag ? <IconActionEditBatchPollDisabled /> : <IconActionEditBatchPoll />}
				</span>
			</div>
			<Search
				className="search"
				iconAlign="left"
				placeholder={t('搜索与会方')}
				value={searchVal}
				onChange={(e, v) => handleSearch(v)}
				onClear={() => handleSearch('')}
				width={276}
				clearable
			></Search>
			<div className="content-wrap">
				<div className="member-list">
					<AutoSizer>
						{({ width, height }) => (
							<DragDropContextProvider>
								<Droppable onDrop={handleDrop} placeholderHeight={38}>
									{(setDroppableRef) => (
										<List
											ref={listRef}
											width={width}
											height={height}
											itemCount={show_pollMembers.length}
											itemSize={38}
											itemData={show_pollMembers}
											itemKey={(index, data) => data[index].mtKey}
											outerRef={setDroppableRef}
										>
											{rowRenderer}
										</List>
									)}
								</Droppable>
							</DragDropContextProvider>
						)}
					</AutoSizer>
				</div>
				<div className="sort_option">
					<span
						className={`move-top ${canDrag && actualSearchVal === '' ? '' : 'disabled'}`}
						onClick={() => {
							if (canDrag && actualSearchVal === '' && poll_select_mt_key_list) {
								handleOrder('top')
							}
						}}
					></span>
					<span
						className={`move-up ${canDrag && actualSearchVal === '' ? '' : 'disabled'}`}
						onClick={() => {
							if (canDrag && actualSearchVal === '' && poll_select_mt_key_list) {
								handleOrder('up')
							}
						}}
					></span>
					<span
						className={`move-down ${canDrag && actualSearchVal === '' ? '' : 'disabled'}`}
						onClick={() => {
							if (canDrag && actualSearchVal === '' && poll_select_mt_key_list) {
								handleOrder('down')
							}
						}}
					></span>
					<span
						className={`move-bottom ${canDrag && actualSearchVal === '' ? '' : 'disabled'}`}
						onClick={() => {
							if (canDrag && actualSearchVal === '' && poll_select_mt_key_list) {
								handleOrder('bottom')
							}
						}}
					></span>
				</div>
			</div>
			<Modal
				open={pollModalIsOpen}
				title={t('轮询方编辑')}
				width={850}
				height={612}
				onOk={okFn}
				onCancel={() => {
					update({ pollModalIsOpen: false })
				}}
				footer={
					<StyledFooter className="footer">
						<span className="msg">
							<IconTips className="icon-tips" />
							{t('可使用ctrl或shift快捷键进行多选')}
						</span>
						<Space>
							<Button onClick={okFn}>{t('确定')}</Button>
							<Button onClick={() => update({ pollModalIsOpen: false })}>{t('取消')}</Button>
						</Space>
					</StyledFooter>
				}
			>
				<PollModal ref={pollModalRef} data={modalList} />
			</Modal>
		</StyledMemberList>
	)
}
